package wechatsmart

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"strconv"
	"time"

	"yundian/internel/pkg/authorized"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

const (
	SmartDialogueURL = "https://openai.weixin.qq.com/openapi"
)

//设置批量导入（普通） https://developers.weixin.qq.com/doc/aispeech/platform/skill/batchimportskill.html
func BatchImportSkill(encryptStr string) (result ErrorRes, err error) {
	urlStr := SmartDialogueURL + "/batchimportskill/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	weChatCpt := NewWXBizMsgCrypt(global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey, global.Cfg.Smart.SmartAppId, XmlType)

	encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(32))
	if cryptErr != nil {
		log.Println("批量导入技能失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result.Code != 0 {
		log.Println("批量导入技能失败", result.Msg)
		return result, err
	}
	return result, nil
}

//机器人发布
func Publish(encryptStr string) (result ErrorRes, err error) {
	urlStr := SmartDialogueURL + "/publish/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	weChatCpt := NewWXBizMsgCrypt(global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey, global.Cfg.Smart.SmartAppId, XmlType)

	encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(32))
	if cryptErr != nil {
		log.Println("机器人发布失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result.Code != 0 {
		log.Println("机器人发布失败", result.Msg)
		return result, err
	}
	return result, nil
}

//机器人发布进度查询
func PublishProgress(encryptStr string) (result map[string]interface{}, err error) {
	urlStr := SmartDialogueURL + "/publish_progress/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	weChatCpt := NewWXBizMsgCrypt(global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey, global.Cfg.Smart.SmartAppId, XmlType)

	encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(32))
	if cryptErr != nil {
		log.Println("机器人发布进度查询失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result["code"].(float64) != 0 {
		log.Println("机器人发布进度查询失败", result)
		return result, err
	}
	return result, nil
}

//设置自动回复
func SetAutoReply(encryptStr string) (result map[string]interface{}, err error) {
	urlStr := SmartDialogueURL + "/setautoreply/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	weChatCpt := NewWXBizMsgCrypt(global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey, global.Cfg.Smart.SmartAppId, XmlType)

	encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(32))
	if cryptErr != nil {
		log.Println("设置自动回复失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result["code"].(float64) != 0 {
		log.Println("设置自动回复失败", result)
		return result, err
	}
	return result, nil
}

//设置批量导入 机器人发布 机器人发布进度查询 设置自动回复 通用接口
func RobotSetting(encryptStr, urlName string) (result map[string]interface{}, err error) {
	urlStr := SmartDialogueURL + "/" + urlName + "/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	we, _ := NewWechatCryptor(global.Cfg.Smart.SmartAppId, global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey)
	encryptMsg, cryptErr := we.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(10))
	if cryptErr != nil {
		log.Println("机器人配置失败", err)
		return result, err
	}

	//encryptMsg, cryptErr := Encrypt(encryptStr)
	//if cryptErr != nil {
	//	log.Println("机器人配置失败", err)
	//	return result, err
	//}

	//weChatCpt := NewWXBizMsgCrypt(helper.SmartToken, helper.SmartEncodingAESKey, helper.SmartAppId, XmlType)
	//
	//encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(10))
	//if cryptErr != nil {
	//	log.Println("机器人配置失败", err)
	//	return result, err
	//}
	//<xml><managerid><![CDATA[d02RJIlc358]]></managerid><skill><skillname><![CDATA[test1]]></skillname><title><![CDATA[test1]]></title><question><![CDATA[嘿嘿]]></question><question><![CDATA[哈哈]]></question><answer><![CDATA[你好]]></answer><answer><![CDATA[嘿嘿]]></answer></skill></xml>
	//encryptMsg = "<xml>\n<Encrypt><![CDATA[Oj1rgi8EYufimO9XH67As26TB9rx/yESmo6xdkYFSIE3CZ7RVyWXsY9NuHmcqMMuwb3G5B1vZKt2HHtRpR672poVaN5jOjAcYOn/eqR/9cCdLTMEqCTqKKwdbVU7Yy0AZj0ejKSNY0dxJcu5nyv3nc91SY03tlXccOUMyV3OSqg9uTAXxSajqw/AkqGkT+djOsWmkCVSRPT0pf7l2AmgnTg9LqsTyNqASLfaK8kivZiz3bXIhChvvvjkm9Qhl5zy0ufiyre8MrlU2mNJTJpD2bRP0hdZEW2YKQhLiV4OCw2hq8f/+1SqC9OxN+LIALxxuyu+gGmi8ieekAHg+i83mU+Nf0ic4rwZmB/mfpePknp2GqvSGJ2oaPVFQelAPFLsIimgynNv7U3VdZc1vVkq1NB/gDGLqhTru4i42SbE+WXf/hJeOmqblzCtde1uB9AlFNI2hOED8eexA7vFTiwXlA==]]></Encrypt>\n<MsgSignature><![CDATA[5eb00571bb2b3446d7d923bb0d7f9471fbd329be]]></MsgSignature>\n<TimeStamp>1637144524</TimeStamp>\n<Nonce><![CDATA[1637144524]]></Nonce>\n</xml>"

	encryptByte, _ := json.Marshal(encryptMsg)

	param.Encrypt = string(encryptByte)

	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(false)
	jsonEncoder.Encode(&param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bf)
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil {
		log.Println("设机器人配置失败", err)
		return result, err
	}
	return result, nil
}

//用户标签批量回传设置
func UserLabelBatchSet(encryptStr string) (result map[string]interface{}, err error) {
	urlStr := SmartDialogueURL + "/label/batchset/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	we, _ := NewWechatCryptor(global.Cfg.Smart.SmartAppId, global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey)

	encryptMsg, cryptErr := we.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(10))
	if cryptErr != nil {
		log.Println("机器人配置失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil || result["code"].(float64) != 0 {
		log.Println("设置自动回复失败", result)
		return result, err
	}
	return result, nil
}

//智能对话接口

//获取signature
func GetSignature(userId string) (result string, err error) {
	urlStr := "https://openai.weixin.qq.com/openapi/sign/" + global.Cfg.Smart.SmartToken

	param := &GetSignatureReq{}

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}
	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)

	res := map[string]interface{}{}
	_ = json.Unmarshal(body, &res)
	if err != nil {
		log.Println("获取signature失败", result)
		return result, err
	}
	result = res["signature"].(string)

	return result, nil
}

//智能对话
func SmartDialogue(query, userId string) (result map[string]interface{}, err error) {
	urlStr := "https://openai.weixin.qq.com/openapi/aibot/" + global.Cfg.Smart.SmartToken
	var signature string
	//获取授权token
	t := global.Rdb.TTL(context.Background(), utils.Join(userId+"-signature")).Val()
	if t <= 0 {
		resSignature, _ := GetSignature(userId)
		signature = resSignature
	} else {
		s := global.Rdb.Get(context.Background(), utils.Join(userId+"-signature")).Val()
		signature = s
	}
	param := &SmartDialogueReq{}

	param.Query = query
	param.Signature = signature
	param.Env = "debug"
	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil {
		log.Println("智能对话失败", result, err)
		return result, err
	}
	return result, nil
}

//获取热问
func GetHotQueryList(encryptStr string) (result map[string]interface{}, err error) {
	urlStr := "https://openai.weixin.qq.com/openapi/gethotquerylist/" + global.Cfg.Smart.SmartToken

	param := &SmartBody{}
	//加密数据
	weChatCpt := NewWXBizMsgCrypt(global.Cfg.Smart.SmartToken, global.Cfg.Smart.SmartEncodingAESKey, global.Cfg.Smart.SmartAppId, XmlType)

	encryptMsg, cryptErr := weChatCpt.EncryptMsg(encryptStr, strconv.Itoa(int(time.Now().Unix())), authorized.GetRandomString(32))
	if cryptErr != nil {
		log.Println("获取热问失败", err)
		return result, err
	}

	param.Encrypt = string(encryptMsg)

	payload, err := json.Marshal(param)
	headers := map[string]string{"Content-Type": "application/json"}

	resp, err := authorized.PostRequest(urlStr, headers, bytes.NewReader(payload))
	body, _ := json.Marshal(resp)
	_ = json.Unmarshal(body, &result)
	if err != nil {
		log.Println("获取热问失败", result, err)
		return result, err
	}
	return result, nil
}
